<!-- 
 * @Author: 汤米淘大米
 * @Date: 2022-06-24
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-08-21
 * @FilePath: /macc.admin.vue/src/project/authSys/views/systemMonitor/index.vue
 * @Description: 
-->
<template>
  <div class="main-content">
    <div>
      <a-row :gutter="16">
        <a-col :span="6">
          <div class="col-item col1">
            <div>{{ $t('privateSys.cpu', [totalData.cpu.cores]) }}</div>
            <div class="item-val">{{ totalData.cpu.usage.toFixed(2) }}%</div>
            <div class="img-item">
              <img src="@assets/images/private/mem.png" alt="" class="img-bg" />
            </div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="col-item col2">
            <div>{{ $t('privateSys.memory') }}</div>
            <div class="item-val">
              {{ totalData.mem.usedPercent.toFixed(2) }}%<span class="item-tip">
                ({{ $t('privateSys.Total') }}:
                {{ dealTotalMem(totalData.mem.total) }}G)</span
              >
            </div>
            <div class="img-item">
              <img src="@assets/images/private/cpu.png" alt="" class="img-bg" />
            </div>
          </div>
        </a-col>
        <a-col :span="6" v-if="totalData.disks.length > 0">
          <div class="col-item col3">
            <div>
              {{ $t('privateSys.disk', { path: defautRootInfo.path }) }}
              <DiskList :tableData="diskList"></DiskList>
            </div>
            <div class="item-val">
              {{ defautRootInfo.usedPercent.toFixed(2) }}%<span
                class="item-tip"
              >
                ({{ $t('privateSys.Total') }}:
                {{ dealTotalDisk(defautRootInfo.total) }}G)</span
              >
            </div>
            <div class="img-item" style="width: 38px">
              <img
                src="@assets/images/private/disk.png"
                alt=""
                class="img-bg"
              />
            </div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="col-item col4">
            <div>{{ $t('privateSys.run') }}</div>
            <div class="item-val">
              {{ totalData.runningTime
              }}<span> {{ $t('privateSys.days') }}</span>
            </div>
            <div class="img-item">
              <img
                src="@assets/images/private/time.png"
                alt=""
                class="img-bg"
              />
            </div>
          </div>
        </a-col>
      </a-row>
      <div class="card-item">
        <div class="sybole1">
          <span class="sybole-tag"></span>{{ $t('privateSys.cpurage') }}
        </div>
        <a-empty v-if="!cpuOptions" :image="simpleImage" />
        <chart :options="cpuOptions" v-else :style="{ height: height + 'px' }">
        </chart>
      </div>
      <div class="card-item">
        <div class="sybole1">
          <span class="sybole-tag"></span>{{ $t('privateSys.memeryrage') }}
        </div>
        <a-empty v-if="!memOptions" :image="simpleImage" />
        <chart :options="memOptions" v-else :style="{ height: height + 'px' }">
        </chart>
      </div>
    </div>
  </div>
</template>

<script>
import { Empty } from 'ant-design-vue';
import {
  requestHttp,
  maccApi,
  fillTimeLineData,
  legendColors,
  legendRect,
  chartOpt,
} from '@utils/index';
import moment from 'moment-timezone';
import publicChart from '@views/common/deviceDetail/components/components/chart/publicChart.vue';
import DiskList from './diskList.vue';
export default {
  name: 'system',
  components: {
    chart: publicChart,
    DiskList,
  },
  data() {
    return {
      labelSpan: 6,
      height: 280,
      sysData: {
        cpu: 0,
        memory: 0,
        disk: 0,
        run: 0,
        total: 0,
      },
      sn: '',
      totalData: {
        cpu: {
          usage: 0,
          cores: 0,
        },
        mem: {
          total: 0,
          used: 0,
          usedPercent: 0,
        },
        runningTime: '',
        disks: [
          {
            path: '/',
            total: 0,
            free: 0,
            used: 0,
            usedPercent: 0,
          },
        ],
      },
      defautRootInfo: {
        path: '/',
        total: 0,
        free: 0,
        used: 0,
        usedPercent: 0,
      },
      cpuOptions: null,
      memOptions: null,
      type: 'MACC', //MACC的系统监控 认证的系统监控
      defautRoot: '/macc', //磁盘显示默认路径 私有云是macc下的
      diskList: [],
    };
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
  mounted() {
    this.initView();
  },
  methods: {
    initView() {
      this.getTotalData();
      this.getCpuSystrend();
      this.getMemSystrend();
    },
    async getTotalData() {
      let res = await requestHttp({
        api: maccApi.MACC_RESOURCE_GET_API,
        method: 'GET',
      });
      if (res.code != 0) {
        if (res.code > 0) this.$message.error(res.msg);
        return;
      } else {
        this.dealDisk(res.data.disks || []);
        this.totalData = res.data;
      }
    },
    dealDisk(diskList) {
      let rootTop = null;
      let exit = false; //是否存在默认的路径
      for (let i = 0; i < diskList.length; i++) {
        if (diskList[i].path == this.defautRoot) {
          this.defautRootInfo = diskList[i];
          exit = true;
          break;
        } else if (diskList[i].path == '/') {
          rootTop = diskList[i];
        }
      }
      if (!exit && rootTop) {
        this.defautRootInfo = rootTop;
      }
      this.diskList = diskList;
    },

    dealTotalMem(val) {
      let total = (val / 1024 / 1024 / 1024).toFixed(2);
      return total;
    },
    dealTotalDisk(val) {
      let total = (val / 1000 / 1000 / 1000).toFixed(2);
      return total;
    },
    //CPU
    async getCpuSystrend() {
      const res = await requestHttp({
        api: maccApi.MACC_CPU_GET_API,
        method: 'GET',
      });
      if (res.code != 0) {
        this.$message.error(res.msg);
        return;
      }
      if (res.data && res.data.data.length > 0) {
        let title = this.$t('privateSys.cpuUtilization1');
        this.cpuOptions = this.dealData(res.data.data, title);
      } else {
        this.cpuOptions = null;
      }
    },
    async getMemSystrend() {
      const res = await requestHttp({
        api: maccApi.MACC_MEMORY_GET_API,
        method: 'GET',
      });
      if (res.code != 0) {
        this.$message.error(res.msg);
        return;
      }
      if (res.data && res.data.data.length > 0) {
        let title = this.$t('privateSys.memoryUtilization');
        this.memOptions = this.dealData(res.data.data, title);
      } else {
        this.memOptions = null;
      }
    },
    dealData(data, title) {
      const end = new Date().getTime();
      const start = end - 24 * 60 * 60 * 1000;
      if (data.length > 0) {
        let gatherTimeList = [];
        let listData = [];
        const list = fillTimeLineData(
          data,
          start,
          end,
          'timestamp',
          1 * 60,
          10 * 1 * 60
        );
        for (const key in list) {
          let zoneTime = moment(list[key].timestamp).format(
            'YYYY/MM/DD HH:mm:ss'
          );
          if (this.timezone) {
            zoneTime = moment
              .tz(list[key].timestamp, this.timezone)
              .format('YYYY/MM/DD HH:mm:ss');
          }
          gatherTimeList.push(zoneTime);
          let val = list[key].usedPercent || list[key].usage;
          if (val != undefined) {
            listData.push(val.toFixed(2));
          } else {
            listData.push('-');
          }
        }
        let options = this.getLineChartOptions(
          {
            timeList: gatherTimeList,
            dataList: listData,
            name: 'systrend',
            title: title,
          },
          title
        );
        return options;
      }
      return null;
    },
    getLineChartOptions(data, title) {
      let self = this;
      let label;
      let option = {
        title: {
          text: '',
          textStyle: {
            fontSize: 14,
            fontStyle: 'normal',
            fontWeight: 'bolder',
          },
        },
        color: legendColors,
        grid: {
          ...chartOpt.grid,
          top: 60,
        },
        legend: {
          ...legendRect,
          show: false,
        },
        tooltip: {
          trigger: 'axis',
          textStyle: {
            align: 'left',
            color: 'rgba(0, 0, 0, 0.65)',
            size: '12px',
          },

          backgroundColor: 'rgba(255,255,255,1)', //设置背景图片 rgba格式
          borderWidth: 0,
          padding: 5,
          formatter: function (params) {
            let res = '';
            let restop = '';
            for (let i = 0; i < params.length; i++) {
              restop = '<span>' + params[i].axisValue + '</span><br/>';
              let data =
                params[i].data == '-'
                  ? '-'
                  : params[i].data + params[i].seriesName;
              res +=
                '<span>' +
                params[i].marker +
                '</span>' +
                title +
                ' : ' +
                data +
                '<br/>';
            }
            return restop + res;
          },
        },
        xAxis: {
          name: self.$t('dataInsight.hour'),
          type: 'category',
          boundaryGap: false,
          axisLine: {
            onZero: false,
          },
          axisTick: {
            show: true,
          },
          axisLabel: {
            formatter: function formatter(value, index) {
              0;

              return moment(value).format('H');
            },
            interval: function interval(index, value) {
              const string = moment(value).format('H');
              if (label != string && parseInt(string) % 2 == 0) {
                label = string;
                return true;
              } else {
                return false;
              }
            },
          },
          data: data.timeList,
        },
        yAxis: [
          {
            name: '%',
            type: 'value',
            axisLine: {
              show: false,
            },
            axisTick: {
              show: true,
            },
            min: 0,
            max: 100,
          },
        ],
        series: [
          {
            name: '%',
            type: 'line',
            smooth: true,
            // areaStyle: {
            //   color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            //     {
            //       offset: 1,
            //       color: 'rgba(255, 255, 255, 1)',
            //     },
            //     {
            //       offset: 0,
            //       color: 'rgba(43, 106, 253, 0.25)',
            //     },
            //   ]),
            // },
            lineStyle: {
              width: 1,
            },
            data: data.dataList,
          },
        ],
      };
      return option;
    },
  },
};
</script>

<style lang="less" scoped>
.main-content {
  background-color: #f0f3f6;
  text-align: left;
  width: 100%；;
  .col-item {
    border-radius: 12px;
    color: @gray-1;
    font-size: 14px;
    font-weight: 500;
    padding: 24px 16px;
    position: relative;
    .item-val {
      font-weight: bold;
      font-size: 24px;
      margin-top: 4px;
    }
    .img-item {
      position: absolute;
      width: 48px;
      right: 16px;
      bottom: 10px;
      .img-bg {
        width: 100%;
      }
    }
  }
  .col1 {
    background: linear-gradient(180deg, #66baf7 0%, #4cb2fc 100%);
  }
  .col2 {
    background: linear-gradient(180deg, #7ea5f2 0%, #719cf3 100%);
  }
  .col3 {
    background: linear-gradient(180deg, #6dc15f 0%, #65b058 100%);
  }
  .col4 {
    background: linear-gradient(180deg, #1dc4ba 0%, #2bb6ad 100%);
  }
  .card-item {
    background-color: @gray-1;
    border-radius: 12px;
    padding: 16px;
    height: 350px;
    margin-top: 16px;
  }
  .sybole1 {
    display: inline-block;
    color: @gray-9;
    font-weight: bold;
    .sybole-tag {
      width: 8px;
      height: 8px;
      transform: rotate(45deg);
      border: 2px solid @ryblue-5;
      margin-right: 8px;
      display: inline-block;
    }
  }
  .item-tip {
    font-size: 12px;
  }
}
</style>
